package com.coszero.utils.file

import android.content.Context
import android.content.Intent
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import com.coszero.utils.utils.LogX
import java.io.BufferedOutputStream
import java.io.BufferedReader
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FileReader
import java.io.IOException
import java.io.InputStream
import java.util.UUID

/**
 * Desc： 文件操作类
 *
 *
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/19 15:23
 * @version 1
 */
object FileUtils {
    /**
     * 获取Assets文件中内容
     *
     * @param context
     * @param path
     * @return
     */
    @JvmStatic
    fun getAssetsData(context: Context, path: String): String {
        var result = ""
        try {
            //获取输入流
            val mAssets = context.assets.open(path)
            //获取文件的字节数
            val lenght = mAssets.available()
            //创建byte数组
            val buffer = ByteArray(lenght)
            //将文件中的数据写入到字节数组中
            mAssets.read(buffer)
            mAssets.close()
            result = String(buffer)
            return result
        } catch (e: IOException) {
            e.printStackTrace()
            LogX.e("#### getAssetsFile Fail", e.message!!)
            return result
        }
    }

    /**
     * 读SD卡中的文件内容
     *
     * @param fname fileName
     * @return 返回文件字符串
     */
    fun readSdFile(fname: String): String {
        val sbf = StringBuilder()
        try {
            val file = File(Environment.getExternalStorageDirectory(), fname)
            if (!file.exists()) {
                return ""
            }
            val br = BufferedReader(FileReader(file))
            var readline: String? = ""
            while ((br.readLine().also { readline = it }) != null) {
                sbf.append(readline)
            }
            br.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sbf.toString()
    }

    /**
     * 读SD卡中的文件内容
     *
     * @param parentPath 目录
     * @param fname fileName
     * @return 返回文件字符串
     */
    fun readSdFile(parentPath: String?, fname: String): String {
        val sbf = StringBuilder()
        try {
            val file = File(parentPath, fname)
            if (!file.exists()) {
                return ""
            }
            val br = BufferedReader(FileReader(file))
            var readline: String? = ""
            while ((br.readLine().also { readline = it }) != null) {
                sbf.append(readline)
            }
            br.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sbf.toString()
    }

    /**
     * 复制文件
     *
     * @param source 输入文件
     * @param target 输出文件
     * @link(use FileControl)
     */
    @Deprecated("")
    fun copy(source: File?, target: File?) {
        FileControl.copy(source, target)
    }

    /**
     * 复制文件
     *
     * @param filename 文件名
     * @param bytes 数据
     */
    @Deprecated("use FileControl")
    fun copy(filename: String, bytes: ByteArray?) {
        FileControl.copy(filename, bytes)
    }

    /**
     * 文件转byte数组
     *
     * @param file
     * @return
     */
    fun File2Bytes(file: File?): ByteArray? {
        val byte_size = 1024
        val b = ByteArray(byte_size)
        try {
            val fileInputStream = FileInputStream(file)
            val outputStream = ByteArrayOutputStream(
                byte_size
            )
            var length: Int
            while ((fileInputStream.read(b).also { length = it }) != -1) {
                outputStream.write(b, 0, length)
            }
            fileInputStream.close()
            outputStream.close()
            return outputStream.toByteArray()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 保存图片
     *
     * @param bm
     * @throws IOException
     */
    @Throws(IOException::class)
    fun saveFile(bm: Bitmap) {
        val dirFile = File(Environment.getExternalStorageDirectory().path)
        if (!dirFile.exists()) {
            dirFile.mkdir()
        }
        val fileName = UUID.randomUUID().toString() + ".jpg"
        var myCaptureFile =
            File(Environment.getExternalStorageDirectory().path + File.separator + "DCIM" + File.separator + "Camera")
        if (!myCaptureFile.exists()) {
            myCaptureFile.mkdirs()
        }
        myCaptureFile =
            File(Environment.getExternalStorageDirectory().path + File.separator + "DCIM" + File.separator + "Camera" + File.separator + fileName)
        val bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos)
        bos.flush()
        bos.close()
        //把图片保存后声明这个广播事件通知系统相册有新图片到来
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri = Uri.fromFile(myCaptureFile)
        intent.setData(uri)
        //        context.sendBroadcast(intent);
    }

    // 创建一个临时目录，用于复制临时文件，如assets目录下的离线资源文件
    fun createTmpDir(context: Context): String {
        val sampleDir = "baiduTTS"
        var tmpDir = Environment.getExternalStorageDirectory().toString() + "/" + sampleDir
        if (!makeDir(tmpDir)) {
            tmpDir = context.getExternalFilesDir(sampleDir)!!.absolutePath
            if (!makeDir(tmpDir)) {
                throw RuntimeException("create model resources dir failed :$tmpDir")
            }
        }
        return tmpDir
    }

    fun makeDir(dirPath: String): Boolean {
        val file = File(dirPath)
        return if (!file.exists()) {
            file.mkdirs()
        } else {
            true
        }
    }

    @Throws(IOException::class)
    fun copyFromAssets(assets: AssetManager, source: String, dest: String, isCover: Boolean) {
        val file = File(dest)
        if (isCover || (!isCover && !file.exists())) {
            var `is`: InputStream? = null
            var fos: FileOutputStream? = null
            try {
                `is` = assets.open(source)
                val path = dest
                fos = FileOutputStream(path)
                val buffer = ByteArray(1024)
                var size = 0
                while ((`is`.read(buffer, 0, 1024).also { size = it }) >= 0) {
                    fos.write(buffer, 0, size)
                }
            } finally {
                if (fos != null) {
                    try {
                        fos.close()
                    } finally {
                        `is`?.close()
                    }
                }
            }
        }
    }

    /**
     * 文件路径转Uri路劲
     *
     * @param file 本地文件
     * @return 返回转化的Uri
     */
    fun FileToUri(file: File?): Uri {
        val uri = Uri.fromFile(file)
        //       return Uri.parse(file.toString());
        return uri
    }
}
